package com.yzcrm.erp.kms.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.yzcrm.common.config.paragetter.BasePageRequest;
import com.yzcrm.common.constant.BaseConstant;
import com.yzcrm.erp.admin.common.AdminMessageEnum;
import com.yzcrm.erp.admin.entity.AdminMessage;
import com.yzcrm.erp.crm.common.CrmEnum;
import com.yzcrm.erp.kms.entity.KmsComment;
import com.yzcrm.utils.AuthUtil;
import com.yzcrm.utils.BaseUtil;
import com.yzcrm.utils.R;

import java.util.ArrayList;
import java.util.List;

/**
 * @author jiang.xue
 */
public class KmsCommentService {

    public R queryCommentPageList(BasePageRequest basePageRequest) {

        JSONObject jsonObject = basePageRequest.getJsonObject();

        Integer label = jsonObject.getInteger("label");
        Integer resourceId = jsonObject.getInteger("resourceId");
        Integer pid = jsonObject.getInteger("pid");
        Integer page = jsonObject.getInteger("page");
        Integer limit = jsonObject.getInteger("limit");
        if(ObjectUtil.isNotNull(page) && ObjectUtil.isNotNull(limit)) {
            page = (page-1)*limit;
        }

        Kv kv = new Kv();
        kv.set("label", label);
        kv.set("resourceId", resourceId);
        kv.set("pid", pid);
        kv.set("page", page);
        kv.set("limit", limit);

        SqlPara sqlPara = Db.getSqlPara("kms.comment.queryCommentPageList", kv);
        List<Record> recordPage = Db.find(sqlPara);

        SqlPara countSql = Db.getSqlPara("kms.comment.queryCommentPageListCount", kv);
        Integer count = Db.queryInt(countSql.getSql(), countSql.getPara());

        // 找到评论的所有回复评论
        recordPage.forEach(record -> {

            Integer isAnonymous = record.getInt("is_anonymous");
            if(ObjectUtil.isNotNull(isAnonymous) && isAnonymous == 1) {
                record.set("create_user_name", "***");
                record.set("create_user_id", "");
            }

            Integer parentIsAnonymous = record.getInt("parent_is_anonymous");
            if(ObjectUtil.isNotNull(parentIsAnonymous) && parentIsAnonymous == 1) {
                record.set("parent_create_user_name", "***");
            }


            String commentId = record.getStr("comment_id");
            List<Record> recordReplay = Db.find(Db.getSql("kms.comment.queryCommentReplayList"), commentId);
            recordReplay.forEach(replay->{
                Integer isAnonymousReplay = replay.getInt("is_anonymous");
                if(ObjectUtil.isNotNull(isAnonymousReplay) && isAnonymousReplay == 1) {
                    replay.set("create_user_name", "***");
                    replay.set("create_user_id", "");
                }

                Integer parentIsAnonymousReplay = replay.getInt("parent_is_anonymous");
                if(ObjectUtil.isNotNull(parentIsAnonymousReplay) && parentIsAnonymousReplay == 1) {
                    replay.set("parent_create_user_name", "***");
                }
            });


            record.set("replays", recordReplay);
        });

//        List<Record> recordPage = Db.find(Db.getSql("kms.comment.queryCommentPageList"), label, resourceId, pid, page, limit);
//        Integer count = Db.queryInt(Db.getSql("kms.comment.queryCommentPageListCount"),  label, resourceId, pid);

        JSONObject resultJsonObject = new JSONObject();
        resultJsonObject.put("list", recordPage);
        resultJsonObject.put("totalRow", count);
        return R.ok().put("data", resultJsonObject);
    }

    public R addComment(JSONObject jsonObject) {

        KmsComment kmsComment = jsonObject.getObject("entity", KmsComment.class);
        if(ObjectUtil.isNull(kmsComment)) {
            return R.error("参数不正确");
        }

        kmsComment.setCreateTime(DateUtil.date());
        kmsComment.setUpdateTime(DateUtil.date());
        kmsComment.setCreateUserId(BaseUtil.getUser().getUserId());
        kmsComment.setStatus(1);
        boolean flag = kmsComment.save();

        // 增加消息
        if(ObjectUtil.isNotEmpty(kmsComment.getPid())) {

            KmsComment kmsCommentParent = KmsComment.dao.findFirst("select * from yzcrm_kms_comment where comment_id = ? ", kmsComment.getPid());
            if(ObjectUtil.isNotNull(kmsCommentParent)) {

                AdminMessage adminMessage = new AdminMessage();
                adminMessage.setContent(kmsComment.getContent());
                adminMessage.setLabel(kmsCommentParent.getLabel());
                if(kmsCommentParent.getLabel() == CrmEnum.KMS_BBS.getType()) {
                    // 评论BBS

                    // 检索BBS标题
                    Record bbs = Db.findFirst(Db.getSql("kms.bbs.queryById"), kmsComment.getResourceId());
                    if(ObjectUtil.isNotNull(bbs)) {
                        adminMessage.setTitle(bbs.get("title"));
                    }

                } else if(kmsCommentParent.getLabel() == CrmEnum.KMS_RESOURCE.getType()) {
                    // 评论资源

                    // 检索资源标题
                    Record resource = Db.findFirst(Db.getSql("kms.resource.queryById"), kmsComment.getResourceId());
                    if(ObjectUtil.isNotNull(resource)) {
                        adminMessage.setTitle(resource.get("title"));
                    }
                }
                adminMessage.setType(AdminMessageEnum.TYPE_COMMENT_REPLAY.getType());
                adminMessage.setTypeId(kmsComment.getCommentId().intValue());
                adminMessage.setCreateUser(BaseUtil.getUserId());
                adminMessage.setCreateTime(DateUtil.date());
                adminMessage.setRecipientUser(kmsCommentParent.getCreateUserId());
                adminMessage.save();
            }
        }

        return flag ? R.ok().put("data", Kv.by("comment_id", kmsComment.getCommentId())) : R.error();
    }

    public R deleteByIds(String commentIds, Integer label){
        String[] idsArr = commentIds.split(",");
        List<Record> idsList = new ArrayList<>();
        for(String id : idsArr){

//            List<Integer> roles = BaseUtil.getUser().getRoles();
//            List<Long> longs = Aop.get(AdminUserService.class).queryUserByAuth(BaseUtil.getUserId(), menuRealm);

            String permissions = "";
            if(CrmEnum.KMS_RESOURCE.getType() == label) {
                permissions = "kms:resource:delete_comment";
            } else if(CrmEnum.KMS_BBS.getType() == label) {
                permissions = "kms:bbs:delete_comment";
            }

            if(!BaseUtil.getUserId().equals(BaseConstant.SUPER_ADMIN_USER_ID) && !BaseUtil.getUser().getRoles().contains(BaseConstant.SUPER_ADMIN_ROLE_ID)
                    && !AuthUtil.isHavaAuth(permissions)
                    && Db.queryInt(Db.getSql("kms.comment.queryIsOwnerUser"), BaseUtil.getUserId(), id) <= 0){
                return R.error("没有权限");
            }


            // 超过24小时不能删除
            KmsComment recoreComment = KmsComment.dao.findFirst("select * from yzcrm_kms_comment where comment_id=?", id);
            Long subHour = (System.currentTimeMillis() - recoreComment.getCreateTime().getTime())/1000/60/60;
            if(!BaseUtil.getUserId().equals(BaseConstant.SUPER_ADMIN_USER_ID) && !BaseUtil.getUser().getRoles().contains(BaseConstant.SUPER_ADMIN_ROLE_ID) &&
                    subHour >= BaseConstant.MAX_DELETE_BBS_HOUR) {
                return R.error("已超过"+BaseConstant.MAX_DELETE_BBS_HOUR+"小时无法删除：" + recoreComment.getContent());
            }


            Record record = new Record();
            idsList.add(record.set("comment_id", Integer.valueOf(id)));
        }

        return Db.tx(() -> {
            Db.batch(Db.getSql("kms.comment.deleteByIds"), "comment_id", idsList, 100);
            return true;
        }) ? R.ok() : R.error();
    }

}
